package com.anxin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.anxin.common.PageResult;
import com.anxin.entity.PatientInfo;
import com.anxin.mapper.PatientInfoMapper;
import com.anxin.service.PatientInfoService;
import com.anxin.system.dto.PatientInfoDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class PatientInfoServiceImpl extends ServiceImpl<PatientInfoMapper, PatientInfo> implements PatientInfoService {


    @Override
    public Page<PatientInfo> page(int pageNum, int pageSize, String realName, String phone) {
        // 创建查询条件构造器
        LambdaQueryWrapper<PatientInfo> wrapper = new LambdaQueryWrapper<>();

        // 根据传入参数动态添加查询条件
        // 如果realName不为空，则对患者姓名进行模糊匹配
        wrapper.like(StringUtils.hasText(realName), PatientInfo::getRealName, realName)
               // 如果phone不为空，则对手机号进行模糊匹配
               .like(StringUtils.hasText(phone), PatientInfo::getPhone, phone)
               // 按创建时间降序排序
               .orderByDesc(PatientInfo::getCreateTime);

        // 执行分页查询并返回结果
        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public PatientInfo getByUserId(String userId) {
        return this.getOne(new LambdaQueryWrapper<PatientInfo>()
                .eq(PatientInfo::getUserId, userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePatientInfo(PatientInfoDTO patientInfoDTO) {
        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setId(patientInfoDTO.getId());
        patientInfo.setUserId(patientInfoDTO.getUserId());
        patientInfo.setRealName(patientInfoDTO.getRealName());
        patientInfo.setIdCard(patientInfoDTO.getIdCard());
        patientInfo.setPhone(patientInfoDTO.getPhone());
        patientInfo.setEmail(patientInfoDTO.getEmail());
        patientInfo.setGender(patientInfoDTO.getGender());
        patientInfo.setBirthDate(patientInfoDTO.getBirthDate());
        patientInfo.setAddress(patientInfoDTO.getAddress());
        this.updateById(patientInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePatientInfo(String id) {
        this.removeById(id);
    }
}
